import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import Weapons from '@/views/Weapons.vue'
import Search from '@/views/Search.vue'
import Login from '@/views/Login.vue'
import Wishlist from '@/views/Wishlist.vue'
import store from '@/store'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    // 如果已经登录，重定向到首页
    beforeEnter: (to, from, next) => {
      if (store.state.auth.isAuthenticated) {
        next('/')
      } else {
        next()
      }
    }
  },
  {
    path: '/arsenal',
    name: 'Arsenal',
    component: Weapons,
    meta: { requiresAuth: true }
  },
  {
    path: '/search',
    name: 'Search',
    component: Search,
    meta: { requiresAuth: true }
  },
  {
    path: '/wishlist',
    name: 'Wishlist',
    component: Wishlist,
    meta: { requiresAuth: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 检查访问的路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 如果需要认证且未登录，重定向到登录页面
    if (!store.state.auth.isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
